package uk.co.wobblycogs.vegas;

import java.io.IOException;
import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Graham Smith
 * @param <T>
 */
public abstract class AbstractService<T extends Serializable> implements Service<T> {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected EntityManagerFactory emf;

	public AbstractService() {
		emf = PersistenceUtilities.getInstance().getEntityManagerFactory();
	}

	@Override
	public void remove(T item) {
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		em.remove(em.merge(item));
		em.getTransaction().commit();
		em.close();
	}

	@Override
	public void persist(T item) {
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		em.persist(item);
		em.getTransaction().commit();
		em.close();
	}

	@Override
	public T merge(T item) {
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		T merged = em.merge(item);
		em.getTransaction().commit();
		em.close();
		return merged;
	}

}
